<?php

class articlesActions extends sfActions {

    public function preExecute(){
        
    }

    public function executeNew(sfWebRequest $request){
        /* inicializamos las variables */
        $c = new Criteria();
        $this->article = null;
        $this->object_is_response = null;
        $this->article_is_response = null;
        /* step es el paso que vamos en la creacion del articulo */
        $step = $request->getParameter('step');
        /* si el paso no se especifica, por defecto es el primero */
        if(!$step){$step='1';}
        if($step=='1'){
            /* revisamos si es respuesta de otro articulo */
            /* $this->object_is_response = ''; */
            $response_of = $request->getParameter('response_of');
            /* creamos un articulo con todo vacío y con is_draft 1. para que se grabe como borrador*/
            /* valida si existe un registro vacío para regresar el mismo id */
            $c->clear();
            $c->add(ArticlePeer::SLUG, '');
            $c->add(ArticlePeer::TITLE, '');
            $c->add(ArticlePeer::SUMMARY, '');
            $c->add(ArticlePeer::CONTENT_FREE, '');
            $c->add(ArticlePeer::CONTENT_PREMIUM, '');
            $c->add(ArticlePeer::SCORE, 0.00);
            $c->add(ArticlePeer::SCORES, 0);
            $c->add(ArticlePeer::RANK, 0);
            $c->add(ArticlePeer::ARTICLE_TYPE_ID, null);
            $c->add(ArticlePeer::COUNTRY_ID, null);
            $c->add(ArticlePeer::LANGUAGE_ID, null);
            $c->add(ArticlePeer::CATEGORY_ID, null);
            $c->add(ArticlePeer::SUBCATEGORY_ID, null);
            $c->add(ArticlePeer::OWNER_ID, $this->getUser()->getAttribute('suid'));
            $c->add(ArticlePeer::ENABLED, 1);
            $c->add(ArticlePeer::IS_DRAFT, 1);
            $c->addDescendingOrderByColumn(ArticlePeer::CREATED_AT);
            $article = ArticlePeer::doSelectOne($c);
            
            if(!is_object($article)){
                $article = new Article();
            }
            $article->setSlug('');
            $article->setTitle('');
            $article->setSummary('');
            $article->setContentFree('');
            $article->setContentPremium('');
            $article->setScore(0.00);
            $article->setScores(0);
            $article->setRank(0);
            $article->setArticleTypeId(null);
            $article->setCountryId(null);
            $article->setLanguageId(null);
            $article->setCategoryId(null);
            $article->setSubcategoryId(null);
            $article->setOwnerId($this->getUser()->getAttribute('suid'));
            $article->setCreatedAt(date("Y-m-d H:i:s"));
            if($response_of){
                $article->setResponseOf($response_of);
            }else{
                $article->setResponseOf(null);
            }
            $article->setIsDraft(1);
            $article->setEnabled(1);
            $article->save();

            $c->clear();
            $c->add(ArticleCostPeer::LAST_COST, null);
            $c->add(ArticleCostPeer::ARTICLE_ID, $article->getId());
            $c->addDescendingOrderByColumn(ArticleCostPeer::CREATED_AT);
            $article_cost = ArticleCostPeer::doSelectOne($c);

            if(!is_object($article_cost)){
                $article_cost = new ArticleCost();
            }
            $article_cost->setLastCost(null);
            $article_cost->setArticle($article);
            $article_cost->setCreatedAt(date("Y-m-d H:i:s"));
            $article_cost->save();

            /* se muestra el artículo para editarlo en tiempo real */
            $this->article = $article;
            $this->article_cost = $article_cost;

            /* revisamos si es borrador y si soy el dueño, sino no muestra */
            /*
            $flag_draft = $request->getParameter('draft');
            if($flag_draft=='true'){
                $draft_id = $request->getParameter('id');
                $draft_obj = TmpArticleDraftPeer::retrieveByPK($draft_id);
                if($draft_obj->getOwnerId()!= $this->getUser()->getAttribute('suid')){
                    $this->redirect('@myArticles');
                }
                $this->getUser()->setAttribute('sparam_draft_id',$draft_id);
                $this->object = $draft_obj;
            }else{
                $this->object = '';
                $draft_obj = '';
            }*/

            $array_users = array();
            if($response_of!=''){/* si no es vacio */
                $eval_response_obj = ArticlePeer::retrieveByPK($response_of);
                if(is_object($eval_response_obj)){/* si existe es porque el articulo a responder existe */
                    //$this->getUser()->setAttribute('sparam_response_of_id',$response_of);
                    $this->article_is_response = $eval_response_obj;

                    $ids = array();
                    $ids[] = $eval_response_obj->getAccount()->getPractilAccountId();

                    $myLib = new myLib();
                    $array_users = $myLib->getUsersFromPractil($ids);
                }
            }
            $this->array_users = $array_users;
            
            $c->clear();
            $this->article_types = ArticleTypePeer::doSelectWithI18n($c);
            
            $c->clear();
            $c->addDescendingOrderByColumn(CategoryI18nPeer::ID);
            $this->categories = CategoryPeer::doSelectWithI18n($c);

            $c->clear();
            $c->addAscendingOrderByColumn(CountryPeer::NAME);
            $this->countries = CountryPeer::doSelect($c);

            $c->clear();
            $this->languages = LanguagePeer::doSelect($c);
            
            $c->clear();
            $this->costs = CostPeer::doSelect($c);

            /* nos lleva al template step1 */
            return $this->setTemplate('newStep1');
        }
        if($step=='2'){
            /* recibimos los parametros del paso 1 */
            $hdArticleId = $request->getParameter('hdArticleId');
            $hdIsResponseOf = $request->getParameter('hdIsResponseOf');/* si es respuesta a otro articulo */
            $title = $request->getParameter('title');
            $country = $request->getParameter('country');
            $language = $request->getParameter('language');
            $type = $request->getParameter('type');
            $costPub = $request->getParameter('costPub');
            $costSpec = $request->getParameter('costSpec');
            $category = $request->getParameter('category');
            $hdCategory = $request->getParameter('hdCategory');
            $subcategory = $request->getParameter('subcategory');
            $hdSubcategory = $request->getParameter('hdSubcategory');
            $summary = $request->getParameter('summary');
            $content = $request->getParameter('content');
            /* si se graba con categoria/subcategoria sugerida */
            $aux_category = $request->getParameter('aux_category');
            $aux_subcategory = $request->getParameter('aux_subcategory');

            $myLib = new myLib();

            $article = ArticlePeer::retrieveByPK($hdArticleId);
            $article->setSlug($myLib->slugify($title));
            $article->setTitle($title);
            $article->setSummary($summary);
            $article->setContentFree($content);/* mientras es borrador el contenido completo del articulo se guarda en el atributo contentfree */
            $article->setContentPremium('');
            $article->setScore(0.00);
            $article->setScores(0);
            $article->setRank(0);
            $article->setArticleTypeId($type);
            $article->setCountryId($country);
            $article->setLanguageId($language);
            $article->setCategoryId($category);
            $article->setSubcategoryId($subcategory);
            $article->setOwnerId($this->getUser()->getAttribute('suid'));
            $article->setCreatedAt(date("Y-m-d H:i:s"));
            if($hdIsResponseOf){
                $article->setResponseOf($hdIsResponseOf);
            }else{
                $article->setResponseOf(null);
            }
            $article->setIsDraft(1);
            $article->setEnabled(1);

            /* evaluamos categoria */
            $category_final = '';
            if($aux_category==''){
                $category_final = $hdCategory;
            }else{
                $category_object = CategoryPeer::retrieveByPK($hdCategory);
                /* enviamos por email las sugerencias
                 * y le asignamos la categoria OTROS */
                $params = array(
                    'chosse_category_object'=>$category_object,
                    'aux_category'=>$aux_category
                );
                $this->emailSugerenciaCategoria($params);

                $category_final = 1;
            }
            $article->setCategoryId($category_final);

            /* evaluamos subcategoria */
            $subcategory_final = '';
            if($aux_subcategory==''){
                $subcategory_final = $hdSubcategory;
            }else{
                $subcategory_object = SubcategoryPeer::retrieveByPK($hdSubcategory);
                /* enviamos por email las sugerencias
                 * y le asignamos la categoria OTROS */
                $params = array(
                    'chosse_subcategory_object'=>$subcategory_object,
                    'aux_subcategory'=>$aux_subcategory
                );
                $this->emailSugerenciaSubcategoria($params);

                $subcategory_final = 1;
            }
            $article->setSubcategoryId($subcategory_final);

            $article->save();

            $this->article = $article;

            if($type=='1'){/* article_type : publico */
                $final_cost = $costPub;
            }elseif($type=='2'){/* article_type : especializado */
                $final_cost = $costSpec;
            }

            $c->clear();
            $c->add(ArticleCostPeer::ARTICLE_ID, $article->getId());
            $article_cost = ArticleCostPeer::doSelectOne($c);
            $article_cost->setLastCost($final_cost);
            $article_cost->setArticleId($article->getId());
            $article_cost->setCreatedAt(date("Y-m-d H:i:s"));
            $article_cost->save();

            /* convertimos el contenido en un array dividido por cada párrafo */
            $contents = explode("\n", trim($content));
            $array_contents = array();
            /* eliminamos los elementos vacios del array */
            foreach($contents as $content){
                if(trim($content)!=""){
                     array_push($array_contents, $content);
                }
            }
            $this->contents = $array_contents;

            /* nos lleva al template step2 */
            return $this->setTemplate('newStep2');
        }
    }

    public function executeEdit(sfWebRequest $request){
        /* inicializamos las variables */
        $c = new Criteria();
        $this->article = null;
        $this->subcategories = null;
        /* step es el paso que vamos en la edicion del articulo */
        $step = $request->getParameter('step');
        /* si el paso no se especifica, por defecto es el primero */
        if(!$step){$step='1';}
        if($step=='1'){
            /* revisamos si es borrador y si soy el dueño, sino no muestra */
            $article = ArticlePeer::retrieveByPK($request->getParameter('id'));
            if($article->getOwnerId()!= $this->getUser()->getAttribute('suid')){
                $this->redirect('@myArticles');
            }
            $this->article = $article;

            $array_users = array();
            if($article->getResponseOf()!=''){/* si no es vacio */
                $eval_response_obj = ArticlePeer::retrieveByPK($article->getResponseOf());
                if(is_object($eval_response_obj)){/* si existe es porque el articulo a responder existe */
                    //$this->getUser()->setAttribute('sparam_response_of_id',$response_of);
                    $this->article_is_response = $eval_response_obj;

                    $ids = array();
                    $ids[] = $eval_response_obj->getAccount()->getPractilAccountId();
                    
                    $myLib = new myLib();
                    $array_users = $myLib->getUsersFromPractil($ids);
                }
            }
            $this->array_users = $array_users;

            $c->clear();
            $this->article_types = ArticleTypePeer::doSelectWithI18n($c);

            $c->clear();
            $c->addDescendingOrderByColumn(CategoryI18nPeer::ID);
            $this->categories = CategoryPeer::doSelectWithI18n($c);

            $c->clear();
            if(is_object($article) && $article->getCategoryId()!=null){
                $c->addDescendingOrderByColumn(SubcategoryI18nPeer::ID);
                $c->add(SubcategoryPeer::CATEGORY_ID, $article->getCategoryId());
                $this->subcategories = SubcategoryPeer::doSelectWithI18n($c);
            }

            $c->clear();
            $c->addAscendingOrderByColumn(CountryPeer::NAME);
            $this->countries = CountryPeer::doSelect($c);

            $c->clear();
            $this->languages = LanguagePeer::doSelect($c);

            $c->clear();
            $this->costs = CostPeer::doSelect($c);

            $c->clear();
            $c->add(ArticleCostPeer::ARTICLE_ID, $article->getId());
            $c->addDescendingOrderByColumn(ArticleCostPeer::CREATED_AT);
            $this->article_cost = ArticleCostPeer::doSelectOne($c);

            return $this->setTemplate('editStep1');
        }
        if($step=='2'){
            /* recibimos los parametros del paso 1 */
            $hdArticleId = $request->getParameter('hdArticleId');
            $title = $request->getParameter('title');
            $country = $request->getParameter('country');
            $language = $request->getParameter('language');
            $type = $request->getParameter('type');
            $costPub = $request->getParameter('costPub');
            $costSpec = $request->getParameter('costSpec');
            $category = $request->getParameter('category');
            $hdCategory = $request->getParameter('hdCategory');
            $subcategory = $request->getParameter('subcategory');
            $hdSubcategory = $request->getParameter('hdSubcategory');
            $summary = $request->getParameter('summary');
            $content = $request->getParameter('content');
            /* si se graba con categoria/subcategoria sugerida */
            $aux_category = $request->getParameter('aux_category');
            $aux_subcategory = $request->getParameter('aux_subcategory');

            $myLib = new myLib();

            $article = ArticlePeer::retrieveByPK($hdArticleId);
            $article->setSlug($myLib->slugify($title));
            $article->setTitle($title);
            $article->setSummary($summary);
            $article->setContentFree($content);/* mientras es borrador el contenido completo del articulo se guarda en el atributo contentfree */
            $article->setContentPremium('');
            $article->setScore(0.00);
            $article->setScores(0);
            $article->setRank(0);
            $article->setArticleTypeId($type);
            $article->setCountryId($country);
            $article->setLanguageId($language);
            $article->setCategoryId($category);
            $article->setSubcategoryId($subcategory);
            $article->setOwnerId($this->getUser()->getAttribute('suid'));
            $article->setIsDraft(0);
            $article->setEnabled(1);

            /* evaluamos categoria */
            $category_final = '';
            if($aux_category==''){
                $category_final = $hdCategory;
            }else{
                $category_object = CategoryPeer::retrieveByPK($hdCategory);
                /* enviamos por email las sugerencias
                 * y le asignamos la categoria OTROS */
                $params = array(
                    'chosse_category_object'=>$category_object,
                    'aux_category'=>$aux_category
                );
                $this->emailSugerenciaCategoria($params);

                $category_final = 1;
            }
            $article->setCategoryId($category_final);

            /* evaluamos subcategoria */
            $subcategory_final = '';
            if($aux_subcategory==''){
                $subcategory_final = $hdSubcategory;
            }else{
                $subcategory_object = SubcategoryPeer::retrieveByPK($hdSubcategory);
                /* enviamos por email las sugerencias
                 * y le asignamos la categoria OTROS */
                $params = array(
                    'chosse_subcategory_object'=>$subcategory_object,
                    'aux_subcategory'=>$aux_subcategory
                );
                $this->emailSugerenciaSubcategoria($params);

                $subcategory_final = 1;
            }
            $article->setSubcategoryId($subcategory_final);

            $article->save();

            $this->article = $article;

            if($type=='1'){/* article_type : publico */
                $final_cost = $costPub;
            }elseif($type=='2'){/* article_type : especializado */
                $final_cost = $costSpec;
            }

            $c->clear();
            $c->add(ArticleCostPeer::ARTICLE_ID, $article->getId());
            $article_cost = ArticleCostPeer::doSelectOne($c);
            $article_cost->setLastCost($final_cost);
            $article_cost->setArticleId($article->getId());
            $article_cost->setCreatedAt(date("Y-m-d H:i:s"));
            $article_cost->save();

            /* convertimos el contenido en un array dividido por cada párrafo */
            $contents = explode("\n", trim($content));
            $array_contents = array();
            /* eliminamos los elementos vacios del array */
            foreach($contents as $content){
                if(trim($content)!=""){
                     array_push($array_contents, $content);
                }
            }
            $this->contents = $array_contents;

            /* nos lleva al template step2 */
            return $this->setTemplate('editStep2');
        }
    }

    public function executeNewEditSave(sfWebRequest $request){
        $hdArticleId = $request->getParameter('hdArticleId');
        $article = ArticlePeer::retrieveByPK($hdArticleId);

        $content = $article->getContentFree();
        /* convertimos el contenido en un array dividido por cada párrafo */
        $contents = explode("\n", trim($content));
        $array_contents = array();
        /* eliminamos los elementos vacios del array */
        foreach($contents as $content){
            if(trim($content)!=""){
                 array_push($array_contents, $content);
            }
        }

        /* recibimos los parametros del paso 2 */
        $hdparagraphs = $request->getParameter('hdparagraphs');
        $hdparagraphs_array = preg_split('/,/', $hdparagraphs);
        /* detectamos en que indice del array de contenidos se encuentra el joker */
        $cont=0;
        foreach($hdparagraphs_array as $p){
            if($p=='joker'){
                $joker_idx = $cont;
            }
            $cont++;
        }
        $content_free = '';
        $content_premium = '';
        /* separamos el contenido en 2 partes, segun el joker (free y premium) */
        foreach($array_contents as $key=>$value){
            if($key<$joker_idx){
                /* content free */
                $content_free .= $array_contents[$key];
            }else{
                /* content premium */
                $content_premium .= $array_contents[$key];
            }
        }

        /* finalizar creacion insertando contenidos free y premium */
        $article->setContentFree($content_free);
        $article->setContentPremium($content_premium);
        $article->setIsDraft(1);
        $article->save();

        /* se actualizan los registros del pais elegido y la categoria + subcategoria, para que sean visibles */
        $this->initCountry($article->getCountryId());
        $this->initCountryCategory($article->getCountryId(), $article->getCategoryId());
        $this->initCountrySubcategory($article->getCountryId(), $article->getSubcategoryId());

        $this->redirect('@postSaved?id='.$article->getId());
    }

    public function executeDiscard(sfWebRequest $request){
        $article_id = $request->getParameter('id');
        $article = ArticlePeer::retrieveByPK($article_id);
        if($article->getOwnerId()==$this->getUser()->getAttribute('suid')){
            $c = new Criteria();
            $c->add(ArticleCostPeer::ARTICLE_ID, $article->getId());
            ArticleCostPeer::doDelete($c);
            ArticlePeer::doDelete($article_id);
        }
        $this->redirect('@myArticles');
    }

    public function executePublish(sfWebRequest $request){
        $article_id = $request->getParameter('id');
        $article = ArticlePeer::retrieveByPK($article_id);
        if($article->getOwnerId()==$this->getUser()->getAttribute('suid')){
            $article->setIsDraft(0);
            $article->save();
        }
        $this->redirect('@myArticles');
    }

    private function initCountry($countryId){
        $country = CountryPeer::retrieveByPK($countryId);
        $country->setIsShown(1);
        $country->save();
    }

    private function initCountryCategory($countryId, $categoryId){
        /* inicializa para que aparezcan las categorias por cada país */
        $c = new Criteria();
        $c->add(DetCountryCategoryPeer::COUNTRY_ID, $countryId);
        $c->add(DetCountryCategoryPeer::CATEGORY_ID, $categoryId);
        $category = DetCountryCategoryPeer::doSelectOne($c);
        if(!is_object($category)){
            $new_obj = new DetCountryCategory();
            $new_obj->setCountryId($countryId);
            $new_obj->setCategoryId($categoryId);
            $new_obj->setIsShown(1);
            $new_obj->save();
        }else{
            $category->setIsShown(1);
            $category->save();
        }
    }

    private function initCountrySubcategory($countryId, $subcategoryId){
        /* inicializa para que aparezcan las subcategorias por cada país */
        $c = new Criteria();
        $c->add(DetCountrySubcategoryPeer::COUNTRY_ID, $countryId);
        $c->add(DetCountrySubcategoryPeer::SUBCATEGORY_ID, $subcategoryId);
        $subcategory = DetCountrySubcategoryPeer::doSelectOne($c);
        if(!is_object($subcategory)){
            $new_obj = new DetCountrySubcategory();
            $new_obj->setCountryId($countryId);
            $new_obj->setSubcategoryId($subcategoryId);
            $new_obj->setIsShown(1);
            $new_obj->save();
        }else{
            $subcategory->setIsShown(1);
            $subcategory->save();
        }
    }

    private function emailSugerenciaCategoria($params){
        $message = $this->getMailer()->compose();
        $message->setSubject('(Opinics) Sugerencia de categoría');
        $message->setTo(sfConfig::get('app_email_suggestions'));
        $message->setFrom(array(sfConfig::get('app_email_no-reply') => 'no-reply'));
        $html = $this->getPartial('mailing/suggestionCategory', array(
            'chosse_category_object'=>$params['chosse_category_object'],
            'aux_category'=>$params['aux_category']));
        $message->setBody($html, 'text/html');
        $this->getMailer()->send($message);
    }

    private function emailSugerenciaSubcategoria($params){
        $message = $this->getMailer()->compose();
        $message->setSubject('(Opinics) Sugerencia de subcategoría');
        $message->setTo(sfConfig::get('app_email_suggestions'));
        $message->setFrom(array(sfConfig::get('app_email_no-reply') => 'no-reply'));
        $html = $this->getPartial('mailing/suggestionSubcategory', array(
            'chosse_subcategory_object'=>$subcategory_object,
            'aux_subcategory'=>$this->getUser()->getAttribute('sparam_aux_subcategory')));
        $message->setBody($html, 'text/html');
        $this->getMailer()->send($message);
    }

    public function executeDelete(sfWebRequest $request){
        $id = $request->getParameter('id');
        $c = new Criteria();
        /* deshabilitamos el articulo */
        $object = ArticlePeer::retrieveByPK($id);
        $object->setEnabled(0);
        $object->save();
        $this->redirect('@myArticles');
    }

    public function executeShow(sfWebRequest $request){
        $id = $request->getParameter('id');
        $article_id = $id;
        $slug = $request->getParameter('slug');
        $c = new Criteria();
        $c->add(ArticlePeer::ID, $id);
        $c->add(ArticlePeer::SLUG, $slug);
        $c->add(ArticlePeer::ENABLED, 1);
        $c->add(ArticlePeer::IS_DRAFT, 0);
        $object = ArticlePeer::doSelectOne($c);
        if(!is_object($object)){
            return sfView::ERROR;
        }
        $this->article = $object;
        $article = $object;/* es necesario */

        /* aumentamos el numero de visitas */
        $article_view = new ArticleViews();
        $article_view->setIp($_SERVER['REMOTE_ADDR']);
        $article_view->setArticleId($id);
        $article_view->setCreatedAt(time());
        $article_view->save();

        $article_cost = '';
        if($this->getUser()->isAuthenticated()){
            /* consultamos si el usuario ha pagado anteriormente */
            $c->clear();
            $c->add(ArticlePaymentsPeer::ACCOUNT_ID, $this->getUser()->getAttribute('suid'));
            $c->add(ArticlePaymentsPeer::ARTICLE_ID, $id);
            $this->article_payment = ArticlePaymentsPeer::doSelectOne($c);
            /* verificamos si el usuario ya puntuó el articulo */
            $c->clear();
            $c->add(ArticleScoresPeer::ARTICLE_ID, $id);
            $c->add(ArticleScoresPeer::ACCOUNT_ID, $this->getUser()->getAttribute('suid'));
            $article_score = ArticleScoresPeer::doSelectOne($c);
            if(!is_object($article_score)){
                /* si no se ha puntuado, se permite puntuar */
                $can_score = '1';
            }else{
                $can_score = '0';
            }
            $this->can_score = $can_score;
        }
        $c->clear();
        $c->add(ArticleCostPeer::ARTICLE_ID, $object->getId());
        $c->addDescendingOrderByColumn(ArticleCostPeer::CREATED_AT);
        $article_cost = ArticleCostPeer::doSelectOne($c);
        $this->article_cost = $article_cost;

        $c->clear();
        $c->add(ArticlePeer::OWNER_ID, $object->getOwnerId());
        $c->add(ArticlePeer::ID, $object->getId(), Criteria::NOT_EQUAL);
        $c->add(ArticlePeer::ENABLED, 1);
        $c->add(ArticlePeer::IS_DRAFT, 0);
        $this->same_owner_arts = ArticlePeer::doselect($c);

        if($this->getUser()->isAuthenticated()){
            $c = new Criteria();
            $c->add(HistoryPeer::ARTICLE_ID, $id);
            $c->add(HistoryPeer::USER_ID, $this->getUser()->getAttribute('suid'));
            $object = HistoryPeer::doSelectOne($c);
            if(!is_object($object)){
                /* si es nuevo lo registramos en el historial */
                $history = new History();
                $history->setViews(1);
                $history->setArticleId($id);
                $history->setUserId($this->getUser()->getAttribute('suid'));
                $history->setCreatedAt(time());
                $history->save();
            }else{
                /* si ya existia, le aumentamos la cantidad de visitas */
                $object->setViews($object->getViews()+1);
                $object->save();
            }
        }

        /* comentarios del articulo */
        $c->clear();
        $c->add(ArticleCommentPeer::ARTICLE_ID, $id);
        $this->comments = ArticleCommentPeer::doSelect($c);

        /* respuestas al articulo */
        $c->clear();
        $c->add(ArticlePeer::RESPONSE_OF, $article->getId());
        $c->add(ArticlePeer::ENABLED, 1);
        $c->add(ArticlePeer::IS_DRAFT, 0);
        $this->responses = ArticlePeer::doSelect($c);

        /* myFavoriteArticles */
        $array_suattr = $this->getUser()->getAttribute('suattr');
        $array_favArticles = preg_split('/[*]/', $array_suattr[7]);
        $this->already_favorite = in_array($id, $array_favArticles);

        /*crear metodo que reciba ids y devuelva arreglo de usuarios practil */
        $ids = array();
        $ids[] = $article->getAccount()->getPractilAccountId();

        $myLib = new myLib();
        $array_users = array();
        $array_users = $myLib->getUsersFromPractil($ids);

        $this->array_users = $array_users;

        /* Los que han leído este artículo, también han visto */
        $related_articles = $this->getRelatedArticles($article_id, 5);
        $rel_arts = array();
        foreach($related_articles as $ra){
            $rel_arts[] = $ra['article_id'];
        }
        $this->related_articles = ArticlePeer::retrieveByPKs($rel_arts);
    }

    private function getRelatedArticles($article_id, $max = 5){ /* Los que han leído este artículo, también han visto */
        $articles = array();

        $con = Propel::getConnection();

        $query = "
            select %s as id, %s as account_id, %s as article_id, %s as created_at, count(%s) as usuarios_totales
            from %s
            where %s in(
                select %s
                from %s
                where %s in (
                    select %s
                    from %s inner join %s
                        on %s = %s
                    where %s='".$article_id."'
                        and %s = '1' and %s = '0'
                )
            ) and %s <> (".$article_id.")
            group by %s
            order by usuarios_totales desc
            limit %s
        ";

        $query = sprintf($query,
          ArticlePaymentsPeer::ID,
          ArticlePaymentsPeer::ACCOUNT_ID,
          ArticlePaymentsPeer::ARTICLE_ID,
          ArticlePaymentsPeer::CREATED_AT,
          ArticlePaymentsPeer::ACCOUNT_ID,
          ArticlePaymentsPeer::TABLE_NAME,
          ArticlePaymentsPeer::ARTICLE_ID,
          ArticlePaymentsPeer::ARTICLE_ID,
          ArticlePaymentsPeer::TABLE_NAME,
          ArticlePaymentsPeer::ACCOUNT_ID,
          ArticlePaymentsPeer::ACCOUNT_ID,
          ArticlePaymentsPeer::TABLE_NAME,
                ArticlePeer::TABLE_NAME,
                ArticlePeer::ID,
                ArticlePaymentsPeer::ARTICLE_ID,
                ArticlePeer::ENABLED,
                ArticlePeer::IS_DRAFT,
          ArticlePaymentsPeer::ARTICLE_ID,
          ArticlePaymentsPeer::ARTICLE_ID,
          ArticlePaymentsPeer::ARTICLE_ID,
          $max
        );

        $stmt = $con->prepare($query);
        $stmt->execute();

        while($rs = $stmt->fetch(PDO::FETCH_ASSOC))
        {
            $articles[] = array(
                "article_id"=>$rs['article_id']
            );
        }

        return $articles;
    }

    public function executeArticleReadFull(sfWebRequest $request){
        $article_id = $request->getParameter('id');
        /* obtenemos el ultimo registro de precios para el articulo */
        $c = new Criteria();
        $c->add(ArticleCostPeer::ARTICLE_ID, $article_id);
        $c->addDescendingOrderByColumn(ArticleCostPeer::CREATED_AT);
        $obj_article_cost = ArticleCostPeer::doSelectOne($c);
        $actual_article_cost = $obj_article_cost->getLastCost();
        /* descontamos el precio del articulo de su saldo */
        /* WS Practil */
        /* agregamos el pago en la tabla article_payments */
        $object = new ArticlePayments();
        $object->setAccountId($this->getUser()->getAttribute('suid'));
        $object->setArticleId($article_id);
        $object->setArticleCostId($obj_article_cost->getId());
        $object->setCreatedAt(time());
        $object->save();

        $article = ArticlePeer::retrieveByPK($article_id);
        $this->redirect('@article?id='.$article->getId().'&slug='.$article->getSlug());
    }

}